"""
Jython Console with Code Completion

This uses the basic Jython Interactive Interpreter.
The UI uses code from Carlos Quiroz's 'Jython Interpreter for JEdit' http://www.jedit.org
"""
#from javax.swing import *
import os
import traceback
from code import InteractiveInterpreter,sys
from org.python.util import InteractiveConsole
import figure;
__author__ = "Don Coleman <dcoleman@chariotsolutions.com>"

import re
# allows multiple imports like "from java.lang import String, Properties"
_re_from_import = re.compile("from\s+\S+\s+import(\s+\S+,\s?)?")

try:
    True, False
except NameError:
    (True, False) = (1, 0)


      

 
class Console:
    PROMPT = sys.ps1
    PROCESS = sys.ps2
    BANNER = ["NCA Cmd Shell"]
  
    include_single_underscore_methods = False
    include_double_underscore_methods = False

    def __init__(self, desktop, namespace=None):
        """
            Create a Jython Console.
            namespace is an optional and should be a dictionary or Map
        """
        self.desktop=desktop;
        #self.history = History(self)

        if namespace != None:
            self.locals = namespace
        else:
            # key:value pairs for namespacc
            cls = lambda : self.cls(); 
            view = lambda x: self.view(x)
            plot = lambda x,y=None,title=None: figure._plot(self,x,y,title);
            self.locals = {'cls':cls, 'view':view, 'plot':plot }
            
        self.buffer = [] # buffer for multi-line commands                    

        self.interp = Interpreter(self, self.locals)       
        #sys.stdout = StdOutRedirector(self)
        self.interp.runsource('from Matrix import *;from MatrixIO import readmatrix;');
        self.interp.runsource('from NCA import gNCA,Match,RankCheck,Subnetwork;')
        
           # add some handles to our objects
    #    self.locals['console'] = self


    def view(self,x):   
        figure = JInternalFrame(x._name)
        figure.setClosable(True)
        figure.setResizable(True)
        table = JTable(x)
        figure.getContentPane().add(JScrollPane(table))
        figure.pack()
        figure.setVisible(True)
        self.desktop.add(figure)
        figure.setSelected(True)

    def putVar(self,d):
        self.locals.update(d);

#    def cls(self):
#        self.text_pane.setText("");

  
    def doInBackground(self, source):
        
        #x = PyThread(self,self.printPrompt,
        self.interp.runsource(source)
       # pman = ProgressThread
       # self.desktop.threads += [pman]
        #self.text_pane.setEditable(False)
        
        # block input to text_pane, except for ctrl-c which interrupts the thread.
        # 
#        x.addPropertyChangeListener(pman)
#        x.execute();
        
   
    # TODO refactor me
    def write(self, text):
        self.__addOutput(self.infoColor, text)

    def printResult(self, msg):
        """ Prints the results of an operation """
        self.__addOutput(self.text_pane.foreground, "\n" + str(msg))

    def printError(self, msg): 
        self.__addOutput(self.errorColor, "\n" + str(msg))

    def printOnProcess(self):
        """ Prints the process symbol """
        self.__addOutput(self.infoColor, "\n" + Console.PROCESS)

    def printPrompt(self):
        """ Prints the prompt """
      
        self.__addOutput(self.infoColor, "\n" + Console.PROMPT)
        
    def __addOutput(self, color, msg):
        """ Adds the output to the text area using a given color """
        pass

    
class Interpreter(InteractiveInterpreter):
    def __init__(self, console, locals):
        InteractiveInterpreter.__init__(self, locals)
        self.console = console
        
    def write(self, data):
        # send all output to the textpane
        # KLUDGE remove trailing linefeed
        self.console.printError(data[:-1])
        
